import { onMounted, watch, onUnmounted, computed } from 'vue'
import { useStore } from 'vuex'

/**
 * @desc       监听路网类型,地市编码 hook
 * @auther     邓清波
 * @date       2022/11/11
 * @param      { callback } Function 变化即调用
 * @return     void
 * */
function useWatchStore(callback) {
  const store = useStore()
  const isFun = typeof callback === 'function'

  const watchSource = computed(() => ({
    roadType: store.state.config.roadType,
    areaCode: store.state.config.areaCode,
    isProvince: store.state.config.isProvince
  }))

  /**
   * @desc   获取前后对象中变化的key
   * @param  { newValue } Object
   * @param  { oldValue } Object | undefined
   * @returns String |  undefined
   **/
  function getChangeKey(newValue, oldValue) {
    // 上一次为空,必然是第一次触发
    if (!oldValue) return
    for (const key in newValue) {
      if (newValue[key] !== oldValue[key]) {
        return `${key}Change`
      }
    }
  }
  const stop = watch(
    watchSource,
    (newValue, prevValue) => {
      const changeKey = getChangeKey(newValue, prevValue)
      isFun && callback(newValue, changeKey)
    },
    {
      deep: true
    }
  )

  onMounted(() => isFun && callback(watchSource.value))
  onUnmounted(() => stop())
}

export default useWatchStore
